package cn.tonyandmoney.baidu.asr.controller

import android.content.Context
import android.os.IBinder
import cn.tonyandmoney.baidu.asr.callback.EventCallback
import cn.tonyandmoney.baidu.asr.remote.IRecognizerAidlInterface
import com.baidu.speech.EventManager
import com.baidu.speech.EventManagerFactory
import com.baidu.speech.aidl.EventListener
import com.baidu.speech.asr.SpeechConstant
import org.jetbrains.anko.AnkoLogger
import org.jetbrains.anko.info

/**
 * Created by niantuo on 2018/2/8.
 * 控制
 */
class Recognizer(context: Context) : IRecognizerAidlInterface.Stub(), AnkoLogger {

    private val mManager: EventManager by lazy { EventManagerFactory.create(context, "asr") }
    private var isOfflineEngineLoaded = false
    private var isInited = false
    private var mCallback: EventCallback? = null

    init {
        if (isInited) {
            error("还未调用release()，请勿新建一个新类")
            throw RuntimeException("还未调用release()，请勿新建一个新类")
        }
        isInited = true
    }

    override fun loadOfflineEngine(params: String?) {
        info("Debug loadOfflineEngine params:$params")
        mManager.send(SpeechConstant.ASR_KWS_LOAD_ENGINE, params, null, 0, 0)
        isOfflineEngineLoaded = true
    }

    override fun start(params: String?) {
        info("开始录音 .Debug asr params(反馈请带上此行日志):$params")
        mManager.send(SpeechConstant.ASR_START, params, null, 0, 0)
    }

    override fun registerCallback(listener: IBinder?) {
        mCallback = EventCallback(EventListener.Stub.asInterface(listener))
        mManager.registerListener(mCallback)
    }


    override fun stop() {
        info("停止录音")
        mManager.send(SpeechConstant.ASR_STOP, "{}", null, 0, 0)
    }

    override fun cancel() {
        info("取消识别")
        mManager.send(SpeechConstant.ASR_CANCEL, "{}", null, 0, 0)
    }

    override fun release() {
        cancel()
        if (isOfflineEngineLoaded) {
            mManager.send(SpeechConstant.ASR_KWS_UNLOAD_ENGINE, null, null, 0, 0)
            isOfflineEngineLoaded = false
        }
        mManager.unregisterListener(mCallback)
        isInited = false
    }
}